/**
 * 
 */
package net.kong.sns.rest.client.login;

import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import net.kong.org.springframework.util.StringUtils;
import net.kong.sns.rest.client.ClientFactory;
import net.kong.sns.rest.client.InvalidResponseException;
import net.kong.sns.rest.client.KongApiMethod;
import net.kong.sns.rest.client.method.JsonMethodInvokeBase;
import net.kong.sns.rest.client.model.LoginResult;
import net.kong.sns.rest.client.model.UserInfo;
import net.kong.sns.rest.client.rest.HttpResponseContent;

/**
 * @author Wang Yuanming
 */
public class LoginMethodInvoke extends JsonMethodInvokeBase<LoginResult> {

    public LoginMethodInvoke(String username, String password ,String apiSecret) {
        super(KongApiMethod.AUTH_LOGIN);
        setParameter("usernameOrMobile", username);
        setParameter("password", this.encryptPassword(password,apiSecret));
        setParameter("fields", StringUtils.arrayToCommaDelimitedString(UserInfo.Field.values()));
    }
    
    public LoginMethodInvoke(String username, String password,String apiSecret,UserInfo.Field[] fields) {
        super(KongApiMethod.AUTH_LOGIN);
        setParameter("usernameOrMobile", username);
        setParameter("password", this.encryptPassword(password,apiSecret));
        setParameter("fields", StringUtils.arrayToCommaDelimitedString(fields));
    }
    
    private String encryptPassword(String oPassword ,String apiSecret) {
        return DigestUtils.md5Hex(DigestUtils.md5Hex(oPassword).toUpperCase() + apiSecret);
    }

    @Override
    protected LoginResult processJsonResponse(HttpResponseContent responseData) throws InvalidResponseException {
        Object o = reader.read(responseData.getBody());
        Map<String, Object> stringObjectMap = (Map<String, Object>) o;
        LoginResult result = new LoginResult();
        result.initialize(stringObjectMap, LoginResult.Field.valuesSet());
        return result;
    }

}
